package com.zzzzzz.topic.comment;

import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Repository;

import com.google.code.morphia.query.Query;
import com.zzzzzz.common.util.StringPool;
import com.zzzzzz.core.dao.morphia.BaseDao;
import com.zzzzzz.topic.NoSuchCommentException;

@Repository
public class CommentDao extends BaseDao {

	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Comment exists with the primary key ";
	
	public void add(Comment comment) {
		db.save(comment);
	}
	
	public void delete(String commentId) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("_id", ObjectId.massageToObjectId(commentId));
		db.delete(query);
	}
 
	public Comment findById(String commentId) throws NoSuchCommentException {
		Comment comment = db.find(Comment.class, "_id", ObjectId.massageToObjectId(commentId)).get();
		if(comment == null) {
			throw new NoSuchCommentException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + commentId);
		}
		return comment;
	}

	public long findCountByParentId(String parentId) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("parentId", parentId);
		return db.getCount(query);
	}
	
	public List<Comment> findByParentId(String parentId) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("parentId", parentId);
		return query.asList();
	}

	public List<Comment> findByParentId(String parentId, int start, int offset, boolean ascending) {
		Query<Comment> query = db.createQuery(Comment.class);
		String condition = "createDate";
		if(!ascending) {
			condition = StringPool.DASH + condition;
		}
		query.filter("parentId", parentId).limit(offset).offset(start).order(condition);
		return query.asList();
	}
	
	public long findCountByTopicId(String topicId) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("topicId", topicId).filter("parentId", StringPool.BLANK);
		return db.getCount(query);
	}
	
	public List<Comment> findByTopicId(String topicId) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("topicId", topicId).filter("parentId", StringPool.BLANK);
		return query.asList();
	}
	
	public List<Comment> findByTopicId(String topicId, int start, int offset, boolean ascending) {
		Query<Comment> query = db.createQuery(Comment.class);
		String condition = "createDate";
		if(!ascending) {
			condition = StringPool.DASH + condition;
		}
		query.filter("topicId", topicId).filter("parentId", StringPool.BLANK).limit(offset).offset(start).order(condition);
		return query.asList();
	}

	public void editStatus(String commentId, Integer status) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("_id", ObjectId.massageToObjectId(commentId));
		db.update(query, db.createUpdateOperations(Comment.class).set("status", status));
	}

	
	
}